package com.pi.base.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pi.base.common.BasePage;
import com.pi.base.common.BaseResult;
import com.pi.base.common.SearchPage;
import com.pi.base.constant.SysStatics;
import com.pi.base.encrypt.MD5Encrypt;
import com.pi.base.entity.SysRole;
import com.pi.base.entity.SysUser;
import com.pi.base.entity.SysUserExample;
import com.pi.base.service.ISysRoleService;
import com.pi.base.service.ISysUserService;
import com.pi.base.util.DateTimeUtil;
import com.pi.base.util.JsonTool;
import com.pi.base.util.MapBuilder;
import com.pi.base.util.SysValidUtil;
import com.pi.base.util.ValidUtil;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Resource
	private ISysUserService sysUserService;
	@Resource
	private ISysRoleService sysRoleService;
	
	@RequestMapping(value="/doUserPasswordChange",method={RequestMethod.POST})
	@ResponseBody
	public BaseResult doUserPasswordChange(@RequestParam(required=false) String newPwd,
			@RequestParam(required=false)String oldPwd,HttpSession httpSession) throws Exception{
		 String checkMess = SysValidUtil.validPwdUpdate(newPwd, oldPwd);
		 if(checkMess.length() > 0){
			   return BaseResult.newErrorResult(checkMess);
		   }
		SysUser loginUser = this.getLoginedUserInfo(httpSession);
		String newPwdMd5 = MD5Encrypt.md5(newPwd);
		String oldPwdMd5 = MD5Encrypt.md5(oldPwd);
		if(!oldPwdMd5.equals(loginUser.getPassword())){
			return BaseResult.newErrorResult("旧密码错误");
		}
		loginUser.setPassword(newPwdMd5);
		boolean flag = sysUserService.updateUserPwd(loginUser);
		
		if (flag) {
			loginUser.setPassword(newPwdMd5);
			httpSession.setAttribute(SysStatics.WEB_USER_SESSION, loginUser);
			return BaseResult.newSuccessResult("修改成功");
		}
		return BaseResult.newErrorResult("修改失败");
	}
	
	/**
	 * 根据分组ID，获取该分组下面的员工列表
	 * 
	 * @param groupId
	 */
	@RequestMapping(value="/getUserList",method={RequestMethod.POST})
	@ResponseBody
	public String getUserList(@ModelAttribute SearchPage searchPage,HttpSession httpSession,
			String quGroupid,String quName,String quUserstate)  throws Exception{
		Integer groupId = 1;
		SysUser loginUser = this.getLoginedUserInfo(httpSession);
		if(!this.isSupperAdmin(httpSession)){
			groupId = loginUser.getGroupid();
		}
		
		String orderSort ;
		if(!ValidUtil.isBlank(searchPage.getSort())){
			orderSort = new StringBuilder(ValidUtil.camelToUnderline(searchPage.getSort())).append(" ").append(searchPage.getOrder()).toString();
		}else{
			orderSort = "roleId asc ,createTime desc";
		}
		String quNameStr = null;
		if(!ValidUtil.isBlank(quName)){
			quNameStr = new StringBuilder("%").append(quName).append("%").toString();
		}
		
		Map<String,Object> params = new MapBuilder.Builder<Object>().
				map("startIndex",searchPage.getStartIndex()).
				map("rows",searchPage.getRows()).
				map("quName",quNameStr).
				map("quUserstate",quUserstate).
				map("quGroupid",quGroupid).
				map("sort",orderSort).
				map("superAdmin",loginUser.getSuperadmin()).build().map();
		BasePage<SysUser> page = sysUserService.listSysUserByGroupID(params, groupId,this.isSupperAdmin(loginUser));
		return JsonTool.toJsonString(page);
	}
	
	@RequestMapping(value="/checkUserName",method={RequestMethod.POST})
	@ResponseBody
	public String checkUserName(@RequestParam String userName) throws Exception{
		if(ValidUtil.isBlank(userName)){
			return "false";
		}
		SysUser searchUser = new SysUser();
		searchUser.setUsername(userName);
		boolean flag = sysUserService.existSysUserName(searchUser);
		if(flag){
			return "false";
		}
		return "true";
		
	}
	
	/*@RequestMapping(value="/checkUserCode",method={RequestMethod.POST})
	@ResponseBody
	public String checkUserCode(@RequestParam String userCode) throws Exception{
		if(ValidUtil.isBlank(userCode)){
			return "false";
		}
		SysUser searchUser = new SysUser();
		searchUser.setCode(userCode);
		boolean flag = sysUserService.existSysUserName(searchUser);
		if(flag){
			return "false";
		}
		return "true";		
	}*/

	@RequestMapping(value="/doUserAdd",method={RequestMethod.POST})
	@ResponseBody
	public BaseResult doUserAdd(@ModelAttribute SysUser insertUser,HttpSession httpSession) throws Exception{
		if(insertUser == null || ValidUtil.isBlank(insertUser.getUsername()) 
				|| ValidUtil.isBlank(insertUser.getPassword())
				/*|| ValidUtil.isBlank(insertUser.getCode()) */
				|| insertUser.getGroupid() == null
				|| insertUser.getRoleid() == null){
			return BaseResult.newErrorResult("参数错误");
		}
		
		//验证用户名或者工号是否重复
		SysUser searchUser = new SysUser();
		searchUser.setUsername(insertUser.getUsername());
		boolean userNameflag = sysUserService.existSysUserName(searchUser);
		if(userNameflag){
			return BaseResult.newErrorResult("用户名已经存在");
		}
		searchUser.setUsername(null);
		/*searchUser.setCode(insertUser.getCode());*/
		boolean codeflag = sysUserService.existSysUserName(searchUser);
		if(codeflag){
			return BaseResult.newErrorResult("工号已经存在");
		}
		insertUser.setPassword(MD5Encrypt.md5(insertUser.getPassword()));
		insertUser.setUserstate(SysStatics.SysUserState_Normal);
		insertUser.setSuperadmin(SysStatics.SysUser_NotSuperAdmin);
		insertUser.setCreatetime(DateTimeUtil.getCurrDate());
		insertUser.setCreatername(this.getLoginedUserInfo(httpSession).getName());
		insertUser.setType(SysStatics.SYSUSER_TYPE_ADMIN);  //后台管理员类型：1
		return sysUserService.insertSysUser(insertUser);
	}
	
	@RequestMapping(value="/doUserRemove",method={RequestMethod.POST})
	@ResponseBody
	public BaseResult doUserRemove(@RequestParam String userIds) throws Exception{
		if(ValidUtil.isBlank(userIds)){
			return BaseResult.newErrorResult("参数错误");
		}
		List<Integer> userIdList = new ArrayList<Integer>();
		String[] userIdArray = userIds.split(",");
		for(String item : userIdArray){
			userIdList.add(Integer.parseInt(item));
		}
		 sysUserService.deleteSysUsers(userIdList);
		 return BaseResult.newSuccessResult("删除成功");
	}
	
	@RequestMapping(value="/doUserUpdate",method={RequestMethod.POST})
	@ResponseBody
	public BaseResult doUserUpdate(@ModelAttribute SysUser updateUser,HttpSession httpSession)
			throws Exception {
		if (updateUser == null || ValidUtil.isBlank(updateUser.getUsername())
				|| ValidUtil.isBlank(updateUser.getName())
				/*|| ValidUtil.isBlank(updateUser.getCode())*/
				|| updateUser.getId() == null) {
			return BaseResult.newErrorResult("参数错误");
		}
		// 验证用户名或者工号是否重复
		SysUser searchUser = new SysUser();
		searchUser.setId(updateUser.getId());
		searchUser.setUsername(updateUser.getUsername());
		boolean userNameflag = sysUserService.existSysUserName(searchUser);
		if (userNameflag) {
			return BaseResult.newErrorResult("用户名已经存在");
		}
		searchUser.setUsername(null);
		/*searchUser.setCode(updateUser.getCode());*/
		boolean codeflag = sysUserService.existSysUserName(searchUser);
		if (codeflag) {
			return BaseResult.newErrorResult("工号已经存在");
		}
		updateUser.setUpdatername(this.getLoginedUserInfo(httpSession).getName());
		updateUser.setUpdatetime(DateTimeUtil.getCurrDate());
		sysUserService.updateSysUser(updateUser);
		return BaseResult.newSuccessResult("更新成功");
	}
	
	/**
	 * 批量修改用户角色
	 * @return
	 */
	@RequestMapping(value="/doUserRoleSet",method={RequestMethod.POST})
	@ResponseBody
	public BaseResult doUserRoleSet(@RequestParam String userIds,@RequestParam Integer roleId) throws Exception{
		if(ValidUtil.isBlank(userIds)){
			return BaseResult.newErrorResult("请选择用户");
		}
		String[] userIdArray = userIds.split(",");
		List<Integer> userIdList = new ArrayList<Integer>();
		for (String s : userIdArray) {
			userIdList.add(Integer.valueOf(s));
		}
		SysRole role = sysRoleService.getRoleById(roleId);
		if(role == null){
			return BaseResult.newErrorResult("角色不存在");
		}
		sysUserService.userRoleSetByUserIdsAndRoleIdAndName(userIdList, roleId, role.getName());
		return BaseResult.newSuccessResult("更新成功");
	}
	
	/**
	 * 批量修改用户分组
	 * @return
	 */
	@RequestMapping(value="/doUserGroupSet",method={RequestMethod.POST})
	@ResponseBody
	public BaseResult doUserGroupSet(@RequestParam String userIds,@RequestParam Integer groupId) throws Exception{
		if(ValidUtil.isBlank(userIds)){
			return BaseResult.newErrorResult("请选择用户");
		}
		String[] userIdArray = userIds.split(",");
		List<Integer> userIdList = new ArrayList<Integer>();
		for (String s : userIdArray) {
			userIdList.add(Integer.valueOf(s));
		}	
		return sysUserService.userGroupSetByUserIdsAndGroupId(userIdList, groupId);
	}
	
	/**
	 * 批量修改用户密码
	 * @return
	 */
	@RequestMapping(value="/doUserPasswordReset",method={RequestMethod.POST})
	@ResponseBody
	public BaseResult doUserPasswordReset(@RequestParam String userIds) throws Exception{
		if(ValidUtil.isBlank(userIds)){
			return BaseResult.newErrorResult("请选择用户");
		}
		String[] userIdArray = userIds.split(",");
		List<Integer> userIdList = new ArrayList<Integer>();
		for (String s : userIdArray) {
			userIdList.add(Integer.valueOf(s));
		}	
		sysUserService.userPasswordResetByUserIds(userIdList, SysStatics.SYS_PWD);
		return BaseResult.newSuccessResult("更新成功");
	}

	/**
	 * 批量修改用户状态
	 * @return
	 */
	@RequestMapping(value="/doUserStateSet",method={RequestMethod.POST})
	@ResponseBody
	public BaseResult doUserStateSet(@RequestParam String userIds,@RequestParam Integer userState) throws Exception{
		if(ValidUtil.isBlank(userIds)){
			return BaseResult.newErrorResult("请选择用户");
		}
		String[] userIdArray = userIds.split(",");
		List<Integer> userIdList = new ArrayList<Integer>();
		for (String s : userIdArray) {
			userIdList.add(Integer.valueOf(s));
		}	
		sysUserService.userStateSetByUserIds(userIdList, userState);
		return BaseResult.newSuccessResult("更新成功");
	}

}
